/* eslint-disable indent */
'use strict'

const Controller = require('egg').Controller
const dayjs = require('dayjs')
const CryptoJS = require('crypto-js')
const { encrypt, decrypt } = require('../extend/cryptoData')


class AppauthController extends Controller {

    // 获取可用密钥列表
    async list() {
        const { service, helper, request, logger } = this.ctx
        const params = request.body
        if (!params.data || !params.barcode) {
            helper.error(null, '参数错误')
            return
        }
        let strDest = ''
        function valid(minute) {
            const week = dayjs().day()
            const strInput = `${week}[xiaoyao_2024]${minute}`
            strDest = CryptoJS.MD5(strInput).toString()
            if (strDest !== params.data) {
                return false
            }
            return true
        }
        // 新校验接口
        function valid2(barcode) {
            const week = dayjs().day()
            const hour = dayjs().hour()
            const strInput = `${week}[${barcode}]${hour}`
            strDest = CryptoJS.MD5(strInput).toString()
            if (strDest !== params.data) {
                return false
            }
            return true
        }

        let isValid = false
        const minute = dayjs().minute()
        for (let i = minute - 5; i <= minute + 5; i++) {
            if (!valid(i)) {
                // logger.info(`时间 [${i}] 校验失败`)
                continue
            } else {
                isValid = true
                break
            }
        }
        if (!isValid) {
            // 老接口校验失败，尝试新接口校验
            isValid = valid2(params.barcode)
        }

        if (!isValid) {
            helper.error(null, '参数错误')
            return
        }

        const data = [
            'LWnnHPjVlqaaqjuu', // AI助手
            'cPFKWbnUyhxHKcUq', // 全游
            'katFTvbpWUXGszkc', // 小妖
            'HXTEIvtGZHOvAgQN', // 小妖2.0
            'dOemfPSRQnKRsMFi',
            'iLcfBHvhQIqgWAUp' // 测试使用
        ]
        const isEncrypt = this.app.config.aes.isencrypt

        if (isEncrypt) {
            // 加密数据
            const strData = encrypt(JSON.stringify(data), params.barcode, strDest)
            this.ctx.body = {
                code: 0,
                data: strData,
                message: 'SUCCESS'
            }

        } else {
            // 不加密
            this.ctx.body = {
                code: 0,
                data,
                message: 'SUCCESS'
            }
        }
    }
}

module.exports = AppauthController
